package org.taru.ems.common.common;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.taru.ems.common.utils.UuidUtil;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author songz
 * @version 1.0
 * @date 2024-04-03 16:55
 */
@Slf4j
@Api(tags = "通用上传前端控制器")
@RestController
@RequestMapping("/common")
public class CommonUploadController {

    @Value("${my.uploadPath.linux}")
    private String linuxPath;
    @Value("${my.uploadPath.windows}")
    private String windowsPath;
    @Value("${my.uploadPath.relative}")
    private String relative;
    private SimpleDateFormat  sdf = new SimpleDateFormat("yyyy-MM-dd");


    /**
     * 通用上传
     * @param file
     * @return
     */

    @ApiOperation(value = "异步上传")
    @PostMapping("/file/upload")
    public CommonResult upload(MultipartFile file) {
        Assert.isTrue(!file.isEmpty(), "上传文件失败，文件名为空");
        String fileName = file.getOriginalFilename();
        Assert.isTrue(!StringUtils.isEmpty(fileName), "上传文件失败，文件名为空");
        // 文件重命名
        String extension = fileName.substring(fileName.lastIndexOf("."));
        String newFileName = UuidUtil.getUUID() + extension;
        // 文件保存的目录
        String fixedPath = null;
        // 判断系统
        //增加判断 dataType 不同的值上传到不同的目录
        String os = System.getProperty("os.name");
        if (os.toLowerCase().startsWith("win")) {
            fixedPath = windowsPath;
        } else {
            fixedPath = linuxPath;
        }
        String datePath =sdf.format(new Date());
        fixedPath = fixedPath + datePath + "/";
        // 判断文件夹是否存在
        File upload = new File(fixedPath);
        if (!upload.exists()) {
            upload.mkdirs();
        }
        String filePath = fixedPath + newFileName;
        log.debug(filePath);
        try (BufferedOutputStream out = new BufferedOutputStream(
                new FileOutputStream(filePath))) {
            out.write(file.getBytes());
            out.flush();
            newFileName = datePath + "/" + newFileName;
            // 文件web浏览路径
            return  CommonResult.OK("上传成功",new NamePathPair(fileName, relative + newFileName));
        } catch (FileNotFoundException e) {
            throw new RuntimeException("上传文件失败 FileNotFoundException：" + e.getMessage());
        } catch (IOException e) {
            throw new RuntimeException("上传文件失败 IOException：" + e.getMessage());
        }
    }

    public class NamePathPair<K, V> {
        private K name;
        private V url;

        public NamePathPair(K name, V url) {
            this.name = name;
            this.url = url;
        }


        public K getName() {
            return name;
        }

        public V getUrl() {
            return url;
        }
    }

}
